<!-- @format -->

<template>
  <view class="comp-action-sheet-container" v-if="modelValue || localVisible">
    <!-- 遮罩层 -->
    <view 
      class="comp-action-sheet-mask" 
      :class="{ 'comp-action-sheet-mask--visible': animationVisible }" 
      @click="handleMaskClick"
    ></view>
    
    <!-- 操作菜单内容 -->
    <view 
      class="comp-action-sheet" 
      :class="{ 'comp-action-sheet--visible': animationVisible }"
    >
      <!-- 标题区域 -->
      <view class="comp-action-sheet__header" v-if="title || $slots.title">
        <slot name="title">
          <view class="comp-action-sheet__title">{{ title }}</view>
        </slot>
      </view>
      
      <!-- 菜单项列表 -->
      <view class="comp-action-sheet__content">
        <slot>
          <view 
            v-for="(item, index) in items" 
            :key="index"
            class="comp-action-sheet__item"
            :class="{
              'comp-action-sheet__item--disabled': item.disabled,
              [`comp-action-sheet__item--${item.type || 'default'}`]: item.type
            }"
            :style="getItemStyle(item)"
            @click="handleItemClick(item, index)"
          >
            <!-- 图标 -->
            <view class="comp-action-sheet__item-icon" v-if="item.icon">
              <slot :name="`icon-${index}`" :item="item">
                <text class="comp-action-sheet__icon">{{ item.icon }}</text>
              </slot>
            </view>
            
            <!-- 文本 -->
            <view class="comp-action-sheet__item-text">
              {{ item.text }}
            </view>
            
            <!-- 子菜单指示器 -->
            <view class="comp-action-sheet__item-indicator" v-if="item.children && item.children.length > 0">
              <text>›</text>
            </view>
          </view>
        </slot>
      </view>
      
      <!-- 自定义内容区域 -->
      <slot name="content"></slot>
      
      <!-- 取消按钮 -->
      <view class="comp-action-sheet__footer">
        <view 
          class="comp-action-sheet__cancel"
          @click="handleCancel"
        >
          <slot name="cancel-text">{{ cancelText }}</slot>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, watch, nextTick, onMounted, onBeforeUnmount } from 'vue'

// 菜单项接口定义
export interface ActionSheetItem {
  /** 菜单项文本 */
  text: string
  /** 菜单项图标 */
  icon?: string
  /** 菜单项类型 */
  type?: 'default' | 'primary' | 'danger' | 'warning' | 'success'
  /** 是否禁用 */
  disabled?: boolean
  /** 自定义样式 */
  style?: Record<string, string>
  /** 子菜单项 */
  children?: ActionSheetItem[]
  /** 其他自定义属性 */
  [key: string]: any
}

// 组件属性定义
interface Props {
  /** 控制显示隐藏 */
  modelValue?: boolean
  /** 菜单项列表 */
  items?: ActionSheetItem[]
  /** 标题 */
  title?: string
  /** 取消按钮文本 */
  cancelText?: string
  /** 点击遮罩是否关闭 */
  closeOnClickMask?: boolean
  /** 点击菜单项是否自动关闭 */
  closeOnClickItem?: boolean
  /** 动画持续时间(ms) */
  duration?: number
}

// 默认属性
const props = withDefaults(defineProps<Props>(), {
  modelValue: false,
  items: () => [],
  title: '',
  cancelText: '取消',
  closeOnClickMask: true,
  closeOnClickItem: true,
  duration: 300
})

// 事件
const emit = defineEmits<{
  /** 更新显示状态 */
  (e: 'update:modelValue', value: boolean): void
  /** 点击菜单项 */
  (e: 'select', item: ActionSheetItem, index: number): void
  /** 点击取消 */
  (e: 'cancel'): void
  /** 完全打开后 */
  (e: 'opened'): void
  /** 完全关闭后 */
  (e: 'closed'): void
}>()

// 内部状态
const localVisible = ref(false)
const animationVisible = ref(false)
let timer: number | null = null

// 监听 modelValue 变化
watch(() => props.modelValue, (newVal) => {
  if (newVal) {
    open()
  } else {
    close()
  }
})

// 打开菜单
const open = () => {
  localVisible.value = true
  clearTimeout(timer as number)
  
  // 等待 DOM 更新后再添加动画类
  nextTick(() => {
    animationVisible.value = true
    timer = setTimeout(() => {
      emit('opened')
    }, props.duration) as unknown as number
  })
}

// 关闭菜单
const close = () => {
  if (!localVisible.value) return
  
  animationVisible.value = false
  clearTimeout(timer as number)
  
  timer = setTimeout(() => {
    localVisible.value = false
    emit('closed')
  }, props.duration) as unknown as number
}

// 处理遮罩点击
const handleMaskClick = () => {
  if (props.closeOnClickMask) {
    handleCancel()
  }
}

// 处理菜单项点击
const handleItemClick = (item: ActionSheetItem, index: number) => {
  if (item.disabled) return
  
  emit('select', item, index)
  
  if (props.closeOnClickItem) {
    updateVisible(false)
  }
}

// 处理取消按钮点击
const handleCancel = () => {
  emit('cancel')
  updateVisible(false)
}

// 更新显示状态
const updateVisible = (visible: boolean) => {
  emit('update:modelValue', visible)
  if (!visible) {
    close()
  }
}

// 获取菜单项样式
const getItemStyle = (item: ActionSheetItem) => {
  return item.style || {}
}

// 组件挂载时初始化
onMounted(() => {
  if (props.modelValue) {
    open()
  }
})

// 组件卸载前清理定时器
onBeforeUnmount(() => {
  clearTimeout(timer as number)
})

// 暴露方法
defineExpose({
  open,
  close
})
</script>

<style scoped>
.comp-action-sheet-container {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 999;
  overflow: hidden;
}

.comp-action-sheet-mask {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0);
  transition: background-color var(--duration, 300ms) ease;
}

.comp-action-sheet-mask--visible {
  background-color: rgba(0, 0, 0, 0.5);
}

.comp-action-sheet {
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #fff;
  border-radius: 16px 16px 0 0;
  transform: translateY(100%);
  transition: transform var(--duration, 300ms) ease;
  max-height: 70vh;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
}

.comp-action-sheet--visible {
  transform: translateY(0);
}

.comp-action-sheet__header {
  padding: 16px;
  text-align: center;
  border-bottom: 1px solid #eee;
}

.comp-action-sheet__title {
  font-size: 16px;
  font-weight: 500;
  color: #333;
}

.comp-action-sheet__content {
  flex: 1;
  overflow-y: auto;
}

.comp-action-sheet__item {
  display: flex;
  align-items: center;
  padding: 16px;
  font-size: 16px;
  color: #333;
  border-bottom: 1px solid #f5f5f5;
  cursor: pointer;
}

.comp-action-sheet__item:active {
  background-color: #f5f5f5;
}

.comp-action-sheet__item--disabled {
  color: #999;
  cursor: not-allowed;
}

.comp-action-sheet__item--disabled:active {
  background-color: transparent;
}

.comp-action-sheet__item--primary {
  color: #007aff;
}

.comp-action-sheet__item--danger {
  color: #ff3b30;
}

.comp-action-sheet__item--warning {
  color: #ff9500;
}

.comp-action-sheet__item--success {
  color: #4cd964;
}

.comp-action-sheet__item-icon {
  margin-right: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.comp-action-sheet__icon {
  font-size: 20px;
}

.comp-action-sheet__item-text {
  flex: 1;
}

.comp-action-sheet__item-indicator {
  font-size: 20px;
  color: #999;
}

.comp-action-sheet__footer {
  padding: 8px 0;
  border-top: 8px solid #f5f5f5;
}

.comp-action-sheet__cancel {
  padding: 16px;
  text-align: center;
  font-size: 16px;
  color: #333;
  cursor: pointer;
}

.comp-action-sheet__cancel:active {
  background-color: #f5f5f5;
}

/* 条件编译样式 */
/* #ifdef H5 */
.comp-action-sheet {
  max-height: 70vh;
}
/* #endif */

/* #ifdef MP-WEIXIN || MP-ALIPAY || MP-BAIDU || MP-TOUTIAO || MP-QQ */
.comp-action-sheet {
  max-height: 85vh;
}
/* #endif */

/* #ifdef APP-PLUS */
.comp-action-sheet {
  max-height: 80vh;
}
/* #endif */
</style>